package com.flute.icrawler.app.processor.extractor.special;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

import com.flute.icrawler.htmlparser.impl.BasicHtmlParser;
import com.flute.icrawler.framework.framework.CrawlUrl;

public class SixRoomCommentAlgo implements IExtractorBelongingsAlgo {
	private static Logger logger = Logger.getLogger(Ku6CommentAlgo.class);
	private static String commentUrl = "http://6.cn/comments/watch_comment_op.php?method=get&cat=list&pagesize=20&vid=";

	@Override
	public String[] extractor(CrawlUrl url) {
		String[] urls = null;
		try {
			String vid = this.getVideoID(url.getUrl());
			int maxpage = this.getMaxPage(vid);
			urls = new String[maxpage];
			for (int i = 1; i <= maxpage; i++) {
				urls[i - 1] = commentUrl + vid + "&curpage=" + i;
			}
		} catch (Exception e) {
			logger.error(e);
		}
		return urls;
	}

	/**
	 * 视频ID
	 * 
	 * @param url
	 * @return
	 */
	private String getVideoID(String url) {
		return url.substring(url.lastIndexOf('/') + 1, url.lastIndexOf('.'));
	}

	/**
	 * 
	 * @param vid
	 * @return
	 */
	private int getMaxPage(String vid) {
		int maxpage = 1;
		try {
			InputStream in = new BasicHtmlParser().request(commentUrl + vid + "&curpage=1");
			final ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
			int c = -1;
			while ((c = in.read()) != -1) {
				byteArray.write(c);
			}
			in.close();
			String comment = new String(byteArray.toByteArray(), "utf-8");
			Pattern p = Pattern.compile("\\,\\\"recordtotal\\\"\\:(\\d+)\\,\\\"time\\\"\\:");
			Matcher m = p.matcher(comment);
			int count = 1;
			if (m.find()) {
				count = Integer.parseInt(m.group(1));
			}
			return (int) Math.ceil((double) count / 20.0);
		} catch (Exception e) {
			logger.error(e);
		}
		return maxpage;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String[] s = new SixRoomCommentAlgo().extractor(new CrawlUrl(null, "http://6.cn/watch/14420052.html"));
		for (String b : s) {
			System.out.println(b);
		}
	}
}
